window.api = "/moqu-wx-app/";

window.sysUser = {};
window.user={};
var commonImport = {};
commonImport.nesTable = [
    {
        url: "js/plugins/nestable/jquery.nestable.js"
    }
];

commonImport.clipboard=[
    {
        url:"js/plugins/clipboard/clipboard.min.js"
    }
]
commonImport.video = [
    {
        url: "https://vjs.zencdn.net/7.8.2/video-js.css"
    },
    {
        url: "https://vjs.zencdn.net/ie8/1.1.2/videojs-ie8.min.js"
    },
    {
        url: "https://vjs.zencdn.net/7.8.2/video.js"
    }
];


toastr.options = {
    "closeButton": true,
    "debug": false,
    "progressBar": false,
    "positionClass": "toast-bottom-right",
    "onclick": null,
    "showDuration": "500",
    "hideDuration": "500",
    "timeOut": "1200",
    "extendedTimeOut": "1000",
    "showEasing": "swing",
    "hideEasing": "linear",
    "showMethod": "fadeIn",
    "hideMethod": "fadeOut"
};

toastr.call = function (callback) {
    setTimeout(function () {
        callback();
    }, toastr.options.timeOut);
};


function isPermission(p) {
    var data = window.sysUser.sysPermission;
    for (var i = 0; i < data.length; i++) {
        if (p == data[i].code) {
            return true;
        }
    }

    return false;
}


function writeStyle(styleText) {
    var style = document.createElement("style");
    style.appendChild(document.createTextNode(styleText));
    var head = document.getElementsByTagName("head")[0];
    head.appendChild(style);
}


function bootstrapTable(doc, obj) {
    if (obj.responseHandler == null) {
        obj.responseHandler = function (res) {
            if (res.code == 0) {
                return {
                    "rows": res.data.rows,
                    "total": res.data.records,
                    "pageNumber": res.data.page
                }
            } else if (res.code == 1) {
                toastr.error(res.msg);
            }  else if (res.code == 2) {
                noLogin();
                return;
            }else if (res.code == 3) {
                toastr.error("权限不足");
            }
            return {
                "rows": 0,
                "total": [],
                "pageNumber": 0
            }
        }
    }
    if (obj.uniqueId == null) {
        obj.uniqueId = "id";
    }
    if (obj.search == null) {
        obj.search = false;
    }
    if (obj.locale == null) {
        obj.locale = 'zh-CN';
    }
    if (obj.pageList == null) {
        obj.pageList = [10, 20, 30, 50];
    }
    if (obj.sidePagination == null) {
        obj.sidePagination = "server";
    }
    if (obj.method == null) {
        obj.method = "post";
    }

    if (obj.contentType == null) {
        obj.contentType = "application/x-www-form-urlencoded";
    }
    if (obj.ajaxOptions == null) {
        obj.ajaxOptions = {
            headers: {"token": window.sysUser.token}
        }
    }

    obj.queryParamsType = "page";

    if (obj.queryParams == null) {
        obj.queryParams = function (params) {
            if (obj.query == null) {
                obj.query = {};
            }
            obj.query._page = params.pageNumber;
            obj.query._size = params.pageSize;
            obj.query._sortName = params.sortName;
            obj.query._sortOrder = params.sortOrder;
            return obj.query;
        }
    }

    if (obj.pagination == null) {
        obj.pagination = true;
    }
    obj.url = window.api + obj.url;
    if (obj.sortable == null) {
        obj.sortable = true;
    }
    if (obj.sortOrder == null) {
        obj.sortOrder = "asc";
    }
    doc.bootstrapTable(obj);
}

function bootstrapTableBtn(value, row, index, id) {
    var btnArrt = {
        btn: "<div class='table-btn'>",
        joinBtn: function (className, btnName, attr) {
            if (attr == null) {
                attr = "";
            }
            btnArrt.btn += '<button  type="button" ' + attr + '  class="btn btn-primary btn-xs ' + className + '">' + btnName + '</button>';
            return btnArrt;
        },
        toString: function () {
            return btnArrt.btn + "</div>";
        }
    };
    return btnArrt;
}

/**
 * 没有登录只执行一次
 */
var noLoginFlag = false;
var noLogin = function () {
    if (noLoginFlag) {
        return;
    }
    noLoginFlag = true;
    toastr.error("登录失效,请先登录");
    toastr.call(function () {
        var href= window.location.href;
        window.location.href = window.root + "login/login.html?redirect_url="+encodeURIComponent(href);
    });
};

function ajaxGet(obj) {

    $.ajax({
        type: "get",
        contentType: obj.contentType == null ? "application/x-www-form-urlencoded" : obj.contentType,
        url: window.api + obj.url,
        dataType: obj.dataType == null ? 'json' : obj.dataType,
        data: obj.data,
        headers: {"token": window.sysUser.token,"app-token":window.user.token},
        success: function (data) {
            if (data.code == 0) {
                obj.success(data);
            } else if (data.code == 2) {
                noLogin();
            } else if (data.code == 3) {
                toastr.error("权限不足");
            } else {
                toastr.error(data.msg);
            }
        },
        error: function (data) {
            toastr.error(data);
        }
    });
}

function ajaxPost(obj) {
    $.ajax({
        type: "post",
        contentType: obj.contentType == null ? "application/x-www-form-urlencoded" : obj.contentType,
        url: window.api + obj.url,
        data: obj.data,
        dataType: obj.dataType == null ? 'json' : obj.dataType,
        headers: {"token": window.sysUser.token,"app-token":window.user.token},
        success: function (data) {
            if (data.code == 0) {
                obj.success(data);
            } else if (data.code == 2) {
                noLogin();
            } else if (data.code == 3) {
                toastr.error("权限不足");
            } else {
                toastr.error(data.msg);
            }
        },
        error: function (data) {
            toastr.error(data);
        }
    });
}


function ajaxBody(obj) {
    $.ajax({
        type: "post",
        contentType: obj.contentType == null ? "application/json;charset=utf-8" : obj.contentType,
        url: window.api + obj.url,
        data: obj.data,
        dataType: obj.dataType == null ? 'json' : obj.dataType,
        headers: {"token": window.sysUser.token,"app-token":window.user.token},
        success: function (data) {
            if (data.code == 0) {
                obj.success(data);
            } else if (data.code == 2) {
                noLogin();
            } else if (data.code == 3) {
                toastr.error("权限不足");
            } else {
                toastr.error(data.msg);
            }
        },
        error: function (data) {
            toastr.error(data);
        }
    });
}



function getFile(url, call) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', window.api + url, true);//get请求，请求地址，是否异步
    xhr.responseType = "blob"; // 返回类型blob
    xhr.onload = function (data, textStatus, request) {// 请求完成处理函数
        if (this.status === 200) {
            var blob = this.response;// 获取返回值
            call(blob);
        }
    };
    xhr.send();
}

function ajaxBodyBlob(url,data,call){
    var xhr = new XMLHttpRequest();
    xhr.open('post', window.api + url, true);//get请求，请求地址，是否异步
    xhr.setRequestHeader("token",window.sysUser.token);
    xhr.setRequestHeader("content-type","application/json;charset=utf-8");
    xhr.responseType = "blob"; // 返回类型blob
    xhr.onload = function (data, textStatus, request) {// 请求完成处理函数
        if (this.status === 200) {
            call(this);
        }
    };
    xhr.send(JSON.stringify(data));

}

if (typeof DsModule != "undefined") {
//默认点击事件行为
//表格里面删除单条数据
    DsModule.addEvent('click',"e-table-delete", function (e, _this) {
        var id = this.getAttribute("data-id");
        var url = this.getAttribute("url");
        var tableClassName = this.getAttribute("table-class-name");
        if (id == null) {
            toastr.error("删除数据不能为空");
            return;
        }
        swal({
            title: "您确定要删除这条数据吗",
            text: "删除后将无法恢复，请谨慎操作！",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "删除",
            closeOnConfirm: true,
            cancelButtonText: "取消"
        }, function () {
            ajaxGet({
                url: url, data: {id: id}, success: function () {
                    toastr.success("删除成功");
                    if (tableClassName == null) {
                        tableClassName = "bootstrapTable";
                    }
                    _this.$("." + tableClassName).bootstrapTable("refresh");
                }
            })
        });
    })

//表格查询
    DsModule.addEvent('click','e-table-search',function (e, _this) {
        var tableClassName = this.getAttribute("table-class-name");
        var searchParam = this.getAttribute("search-param-class-name");
        if (searchParam == null) {
            searchParam = "search-param";
        }
        if (tableClassName == null) {
            tableClassName = "bootstrapTable";
        }
        var q = _this.toMap("." + searchParam)
        _this.$("." + tableClassName).bootstrapTable("refresh", {query: q, silent: true});
    })

    //表格导出
    DsModule.addEvent('click','e-table-export',function (e, _this) {
        var url = this.getAttribute("url");
        var searchParam = this.getAttribute("search-param-class-name");
        if (searchParam == null) {
            searchParam = "search-param";
        }
        var q = _this.toMap("." + searchParam)
        var exportForm = $("<form target='_blank' action='"+window.api+url+"' method='post' style='display: none'></form>")
        exportForm.append("<input type='hidden' name='token' value='"+window.sysUser.token+"'/>")
        for(var k in q){
            exportForm.append("<input type='hidden' name='"+k+"' value='"+q[k]+"'/>")
        }
        $(document.body).append(exportForm);
        exportForm.submit();
        exportForm.remove();
    })

    //批量删除
    DsModule.addEvent('click','e-table-batch-delete',function (e, _this) {
        var url = this.getAttribute("url");
        var tableClassName = this.getAttribute("table-class-name");
        if (tableClassName == null) {
            tableClassName = "bootstrapTable";
        }
        var rows = _this.$("." + tableClassName).bootstrapTable('getSelections');
        var ids="";
        for(var i=0;i<rows.length;i++){
            ids+=rows[i].id+",";
        }
        if(ids==""){
            toastr.error("删除数据不能为空");
            return;
        }
        ids=ids.substring(0,ids.length-1);
        swal({
            title: "您确定要删除这批数据吗",
            text: "删除后将无法恢复，请谨慎操作！",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "删除",
            closeOnConfirm: true,
            cancelButtonText: "取消"
        }, function () {
            ajaxPost({
                url: url, data: {ids: ids}, success: function () {
                    toastr.success("删除成功");
                    _this.$("." + tableClassName).bootstrapTable("refresh");
                }
            })
        });
    })


}

function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}
